package com.hyk.commonLib.common.utils.dataBinding.bindingAdapter;

import android.view.View;

import androidx.databinding.BindingAdapter;

import com.hyk.commonLib.common.utils.ToastUtil;
import com.hyk.commonLib.common.utils.rx.EmptyObserver;
import com.jakewharton.rxbinding4.view.RxView;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.TimeUnit;

import kotlin.Unit;

/**
 * Created by 贺玉琨 on 2020/7/15.
 */
public class OnDebounceClickAdapter {

    //两次点击间的最小间隔(毫秒)
    private static final int CLICK_WINDOW_DURATION = 300;

    @BindingAdapter(value = {"onDebounceClick", "debounceClickWindow"}, requireAll = false)
    public static void setOnDebounceClick(final View view, final View.OnClickListener listener, Integer debounceClickWindow) {
        view.setOnClickListener(null);
        RxView.clicks(view)
                // 防抖操作
                .throttleFirst((debounceClickWindow == null || debounceClickWindow <= 0) ? CLICK_WINDOW_DURATION : debounceClickWindow, TimeUnit.MILLISECONDS)
                .subscribe(new EmptyObserver<Unit>() {
                    @Override
                    public void onNext(@NotNull Unit unit) {
                        if (listener != null) {
                            listener.onClick(view);
                        }
                    }

                    @Override
                    public void onError(@NotNull Throwable e) {
                        super.onError(e);
                        ToastUtil.getSingleton().showCommonRetryError();
                    }
                });
    }
}
